package top.spray.common.test;

import org.junit.Test;
import reactor.core.publisher.Mono;

public class ReactiveTester {
    @Test
    public void testOnMono() {
        // this will create a mono contains a string object.
        Mono.just("test")
                .handle((content, sink) -> {
                    System.out.println(Thread.currentThread().getName() + ": " + content);
                    boolean isSuccess = true;
                    if (isSuccess) {
                        sink.next(content +  "success");
//                        sink.complete();
                    } else {
                        sink.error(new RuntimeException());
                    }
                })
                .doOnSuccess(content -> System.out.println(Thread.currentThread().getName()
                        + ": success: " + content))
                //
                .subscribe();
        // mostly we use create method to build a mono
        Mono.create(sink -> {
            boolean success = false;
            sink.onRequest(l -> {
                System.out.println("print this on mono is subscribed");
            });
            System.out.println("but actually this will be printed on mono is subscribed too");
            if (success) {
                sink.success("test");
            } else {
                sink.error(new RuntimeException());
            }
        }).subscribe();
        // provide an error mono, it will trigger the error handler of mono.
        Mono.<String>error(new RuntimeException())
                // this will resume the error to a new mono. use this if we need error info
                .onErrorResume(error -> Mono.just("error happened: " + error.getMessage()))

                // this will ignore the error and give a new mono. use this if the error is not in need
                .onErrorReturn("error happened: " + "ignored")

                .handle((content, sink) -> {
                    System.out.println(Thread.currentThread().getName() + ": " + content);
                })

                // this will do like a try catch block, but it will not be triggered
                // if the error has been handled with onErrorResume or onErrorReturn method.
                .doOnError(Throwable::printStackTrace)
                .subscribe();

        Mono<String> mono = Mono.empty();




    }
}
